<?php

/**
 * check user in black list by tong dun interface
 * User: csyr
 * Date: 16/7/23
 * Time: 下午3:05
 */
 
namespace Home\Common\Hook;

use Common\Library\BusinessException;
use Common\Library\Constant;
use Common\Vendor\Hook\BaseHook;
use Think\Log;

class BaiRong extends BaseHook
{
    public function execute($data, $param = [])
    {
        $api_url = 'http://open.dai.zhangfujr.com';
        
        $id_num = $data['id_num'];
        $mobile = $data['mobile'];
        $real_name = $data['real_name'];
        $partnerId = "1701171101005";
        $timestamp = time();
        $secretKey = "120d953a7c450bf90593c4de5a2b566d";
        
        $xml_data = array(
            "partner_id" => $partnerId, // (string) 合作者ID
            "timestamp" => $timestamp, // (string) 请求时间戳(精确到秒)
            "name" => $real_name, // (string) 姓名
            "id_num" => $id_num, // (string) 身份证号
            "mobile" => $mobile
        );
        
        
        $sign = $this->genSign($xml_data);
        $url = $api_url . "/Partner/BlackList/BaiRong";
        $xml_data['sign'] = $sign;
        $res = $this->curlPost($url,$xml_data);
        
        if($res){
            $result_arr = json_decode($res,true);
            if($result_arr) {
                if($result_arr['msg'] == 'reject') {
                    BusinessException::throwException(Constant::IN_BLACK_LIST_BR);
                }
            }
            return $data;
        }else {
            BusinessException::throwException(Constant::INVALID_PARAMETER);
        }
        
    }
    
    function genSign(array $param) {
        //0. 删除原数据中自带的sign值,防止干扰计算结果
        unset($param['sign']);
        //1. 按key由a到z排序
        ksort($param);
        foreach ($param as $key => $value) {
            if (is_array($value)) {
                $param[$key] = $this->genSign($value);
            }
        }
        //2. 生成以&符链接的key=value形式的字符串
        $paramString = urldecode(http_build_query($param));
    
        //3. 拼接我们的服务秘钥，并md5加密
        $sign = md5($paramString . '120d953a7c450bf90593c4de5a2b566d');
        return $sign;
    }
    
    function curlPost($url,$xml_data) {
        $ch=curl_init($url);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        //curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        //curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
    
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($xml_data));
        $response = curl_exec($ch);
        if(curl_errno($ch))
        {
            print curl_error($ch);
        }
        curl_close($ch);
        return $response;
    }
    
    
}